import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ApiException } from '@main/common/exceptions/api.exception';
import SysConfig from '@main/entities/service/admin/sys/sys-config.entity';
import { Like, Repository } from 'typeorm';
import { SysOperationLogService } from '../operationLog/operationLog.service';

@Injectable()
export class SysParamConfigService {
  constructor(
    @InjectRepository(SysConfig)
    private configRepository: Repository<SysConfig>,
    private operationLogService: SysOperationLogService
  ) {
    this.initParamConfig();
  }

  async initParamConfig() {
    const paramConfigList = await this.configRepository.find();

    if (paramConfigList.length === 0) {
      console.log('初始化参数');

      this.configRepository.insert([
        {
          configCode: 'isAdjuest',
          configName: '是否需要调机（0否，1是）',
          configValue: '1',
        },
        {
          configCode: 'isAutoConfirmReportWork',
          configName: '是否开启报工自动确认（0否，1是）',
          configValue: '0',
        },
        {
          configCode: 'isAutoSuccessWork',
          configName: '是否开启自动完工（0否，1是）',
          configValue: '0',
        },
        {
          configCode: 'isOpenUnitOptions',
          configName: '是否开启单元配置（0否，1是）',
          configValue: '0',
        },
        {
          configCode: 'isAutoChangeOrder',
          configName: '是否开启自动换单（0否，1是）',
          configValue: '0',
        },
        {
          configCode: 'labelPrintTop',
          configName: '打印标签空白距离',
          configValue: '300',
        },
        {
          configCode: 'zeroNoSuccessWork',
          configName: '实时产量为0不能完工',
          configValue: '0',
        },
        {
          configCode: 'electricityPrice',
          configName: '电价',
          configValue: '1.5',
        },
        {
          configCode: 'waterPrice',
          configName: '水价',
          configValue: '8',
        },
        {
          configCode: 'attendanceHours',
          configName: '出勤时数',
          configValue: '8',
        },
        // {
        //   configCode: 'pictureUrl',
        //   configName: '服务器图片路径',
        //   configValue: 'http://127.0.0.1:3000/file/',
        // },
      ]);
    }
  }

  /**
   * 罗列所有配置
   */
  async page(data) {
    const { pageSize, pageNum, entity = {} } = data;

    const { configName } = entity;

    return await this.configRepository.findAndCount({
      where: {
        configName: Like(`%${configName}%`),
      },
      order: {
        updateTime: 'DESC',
      },
      take: pageSize,
      skip: (pageNum - 1) * pageSize,
    });
  }

  /**
   * 新增
   */
  async add(data, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    const config = await this.configRepository.insert({
      ...data,
      createName: user.nickName,
      createUserName: user.userName,
      updateName: user.nickName,
      updateUserName: user.userName,
    });
    databaseOperationLogList.push({
      type: 'add',
      dataType: 'obj',
      database: 'SysConfig',
      checkOnlyKeyList: [],
      data: config,
      whereObj: null,
      remark: `SysConfig表新增数据`,
    });
    await this.operationLogService.add(
      {
        type: 'add',
        msg: `参数模块新增参数`,
        databaseOperationLogList,
        remark: `新增参数${data.configName}`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 更新
   */
  async update(data, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    await this.configRepository.update(
      { id: data.id },
      {
        configName: data.configName,
        configValue: data.configValue,
        remark: data.remark,
        updateName: user.nickName,
        updateUserName: user.userName,
      }
    );
    databaseOperationLogList.push({
      type: 'update',
      dataType: 'obj',
      database: 'SysConfig',
      checkOnlyKeyList: [],
      data: {
        configName: data.configName,
        configValue: data.configValue,
        remark: data.remark,
        updateName: user.nickName,
        updateUserName: user.userName,
      },
      whereObj: { id: data.id },
      remark: `SysConfig表更新参数信息`,
    });
    await this.operationLogService.add(
      {
        type: 'update',
        msg: `参数模块更新参数信息`,
        databaseOperationLogList,
        remark: `更新参数${data.configName}`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 删除
   */
  async delete(idList, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    await this.configRepository.delete(idList);
    databaseOperationLogList.push({
      type: 'delete',
      dataType: 'array',
      database: 'SysConfig',
      checkOnlyKeyList: [],
      data: null,
      whereObj: idList,
      remark: `SysConfig表删除参数`,
    });
    await this.operationLogService.add(
      {
        type: 'delete',
        msg: `参数模块删除参数`,
        databaseOperationLogList,
        remark: `删除参数`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 查询单个
   */
  async info({ configCode }) {
    return await this.configRepository.findOne({ where: { configCode } });
  }

  async listInfo(configCodeList) {
    const list = [];

    for (let i = 0; i < configCodeList.length; i++) {
      list.push(await this.configRepository.findOne({ where: { configCode: configCodeList[i] } }));
    }

    return list;
  }

  async isExistKey(configCode: string) {
    const result = await this.configRepository.findOne({ where: { configCode } });

    if (result) {
      throw new ApiException(10035);
    }
  }

  async findValueByCode(configCode: string) {
    const result = await this.configRepository.findOne({
      where: { configCode },
      select: ['configValue'],
    });

    return result?.configValue || null;
  }
}
